"""
日志管理模块
"""

import logging
import os
from pathlib import Path
from logging.handlers import RotatingFileHandler
from typing import Dict, Any

def setup_logger(config: Dict[str, Any]) -> logging.Logger:
    """设置日志记录器"""
    
    # 创建日志目录
    log_file = config.get('file', 'logs/processing.log')
    log_dir = Path(log_file).parent
    log_dir.mkdir(parents=True, exist_ok=True)
    
    # 创建日志记录器
    logger = logging.getLogger('image_cropping_system')
    logger.setLevel(getattr(logging, config.get('level', 'INFO')))
    
    # 清除现有处理器
    logger.handlers.clear()
    
    # 创建格式化器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # 文件处理器
    max_size = _parse_size(config.get('max_size', '10MB'))
    backup_count = config.get('backup_count', 5)
    
    file_handler = RotatingFileHandler(
        log_file,
        maxBytes=max_size,
        backupCount=backup_count,
        encoding='utf-8'
    )
    file_handler.setLevel(getattr(logging, config.get('level', 'INFO')))
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    
    return logger

def _parse_size(size_str: str) -> int:
    """解析大小字符串"""
    size_str = size_str.upper()
    if size_str.endswith('KB'):
        return int(size_str[:-2]) * 1024
    elif size_str.endswith('MB'):
        return int(size_str[:-2]) * 1024 * 1024
    elif size_str.endswith('GB'):
        return int(size_str[:-2]) * 1024 * 1024 * 1024
    else:
        return int(size_str)